import 'package:cached_network_image/cached_network_image.dart';
import 'package:dartx/dartx.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:gluz/app/data/shop/shop_category_entity.dart';
import 'package:gluz/app/data/shop/shop_list_entity.dart';
import 'package:gluz/app/utils/toast_util.dart';
import 'package:gluz/app/utils/colors.dart';

import '../../../../app_session.dart';
import '../../../routes/app_pages.dart';

class ShopController extends GetxController with GetTickerProviderStateMixin {
  // 页面级tab索引
  final selectedTabIndex = 0.obs;

  // 二级分类索引
  final selectedSecondaryIndex = 0.obs;

  // TabController for secondary categories
  TabController? tabController;

  List<String> aspectRatioList = [
    '家装用品',
    '配件用品',
    '日用百货',
    '电子产品',
    '生鲜食品',
    '洗护用品',
    '玩具乐器',
    '车辆用品',
    '体育用品',
    '机械设备',
    '配饰用品',
    '宠物用品',
    '服饰配件',
    '其他物品',
    '医疗器械',
    '五金工具',
    '其他',
    '1688',
  ];

  // 一级分类数据
  List<ShopCategoryEntity> primaryCategories = [];

  // 二级分类数据
  List<ShopCategoryEntity> secondaryCategories = [];

  // 商品数据
  List<ShopListEntity> products = [];

  // 分页相关
  int pageSize = 100;
  int currentPage = 0;
  bool isLoadingMore = false;
  bool hasMoreData = true;
  int? currentClassId;

  // 筛选相关
  String sortType = '1'; // 默认按查看降序
  final Map<String, String> sortOptions = {
    '1': '查看升序',
    '2': '查看降序',
    '3': '价格升序',
    '4': '价格降序',
  };

  @override
  void onInit() {
    super.onInit();
    // 不在这里初始化TabController，等有数据时再创建
    _loadPrimaryCategoriesData();
  }

  @override
  void onReady() {
    super.onReady();
  }

  @override
  void onClose() {
    tabController?.dispose();
    super.onClose();
  }

  // 加载数据
  Future<void> _loadPrimaryCategoriesData() async {
    ToastUtil.showLoading();
    List<ShopCategoryEntity> primaryCategories = await app.getShopCategory(
      useCache: false,
    );
    primaryCategories.forEach((element) {
      if (aspectRatioList.contains(element.name)) {
        element.aspectRatio = 1.5;
      }
    });
    this.primaryCategories = primaryCategories;
    if (primaryCategories.isNotEmpty) {
      _loadSecondsCategoriesData(primaryCategories.first.id.toInt());
    }
    update();
  }

  Future<void> _loadSecondsCategoriesData(int pId) async {
    // 先清空当前数据
    secondaryCategories = [];
    tabController?.dispose();
    tabController = null;

    // 加载新的二级分类数据
    ToastUtil.showLoading();
    secondaryCategories = await app.getShopCategory(useCache: false, pId: pId);
    selectedSecondaryIndex.value = 0;

    if (secondaryCategories.isNotEmpty) {
      // 创建新的TabController
      tabController = TabController(
        length: secondaryCategories.length,
        vsync: this,
        initialIndex: 0,
      );
      // 确保TabController创建后再加载商品数据
      await _filterProductsByCategory(secondaryCategories[0].id.toInt());
    } else {
      ToastUtil.dismiss();
      logger.e('没有找到二级分类数据');
    }
    update(); // 最终更新UI
  }

  // 页面级tab切换
  void onTabChanged(int index) {
    selectedTabIndex.value = index;
    // 根据tab切换加载不同的数据
    _loadDataByTab(index);
  }

  // 根据tab加载数据
  void _loadDataByTab(int tabIndex) {
    // 这里后续会根据不同的tab加载不同的数据
    switch (tabIndex) {
      case 0: // 商品
        break;
      case 1: // 其他
        break;
    }
  }

  // 搜索按钮点击
  void onSearchTap() {
    Get.toNamed('/search');
  }

  // 一级分类点击
  void primaryCategory(ShopCategoryEntity category) {
    _loadSecondsCategoriesData(category.id.toInt());
  }

  // 二级分类点击
  void onSecondaryCategoryTap(int index) {
    selectedSecondaryIndex.value = index;
    // 根据分类筛选商品
    if (index < secondaryCategories.length) {
      ToastUtil.showLoading();
      _filterProductsByCategory(secondaryCategories[index].id.toInt());
    }
    update();
  }

  // 根据分类筛选商品
  Future<void> _filterProductsByCategory(int classId) async {
    // 重置分页状态
    currentPage = 0;
    hasMoreData = true;
    isLoadingMore = false;
    currentClassId = classId;
    ToastUtil.showLoading();
    Map<String, dynamic> resMap = {};
    List<ShopListEntity>? products = await app.http.request(
      path: '/api/mall/getProductList',
      params: {
        'pageSize': pageSize,
        'pageNum': currentPage,
        'classId': classId,
        'productSort': sortType, // 添加排序参数
      },
      fromJson: (e) {
        resMap = e;
        List listMap = resMap['records'];
        return listMap.map((obj) {
          return ShopListEntity.fromJson(Map<String, dynamic>.from(obj));
        }).toList();
      },
    );
    ToastUtil.dismiss();
    this.products = products ?? [];

    // 检查是否还有更多数据
    int total = resMap['total'] ?? 0;
    if (this.products.length == total) {
      hasMoreData = false;
    }
    update();
  }

  // 加载更多商品
  Future<void> loadMoreProducts() async {
    if (isLoadingMore || !hasMoreData || currentClassId == null) {
      return;
    }

    isLoadingMore = true;
    currentPage++;

    Map<String, dynamic> resMap = {};
    try {
      List<ShopListEntity>? newProducts = await app.http.request(
        path: '/api/mall/getProductList',
        params: {
          'pageSize': pageSize,
          'pageNum': currentPage,
          'classId': currentClassId,
          'productSort': sortType, // 添加排序参数
        },
        fromJson: (e) {
          resMap = e;
          List listMap = e['records'];
          return listMap.map((obj) {
            return ShopListEntity.fromJson(Map<String, dynamic>.from(obj));
          }).toList();
        },
      );

      int total = resMap['total'] ?? 0;
      if (newProducts != null && products.length < total) {
        products.addAll(newProducts);
      } else {
        hasMoreData = false;
      }
    } catch (e) {
      logger.e('加载更多商品失败: $e');
      currentPage--; // 回退页码
    } finally {
      isLoadingMore = false;
      update();
    }
  }

  // 筛选按钮点击
  void onFilterTap() {
    Get.bottomSheet(
      _buildFilterBottomSheet(),
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
    );
  }

  // 关闭筛选弹窗
  void closeFilter() {
    Get.back();
  }

  // 选择排序方式
  void selectSortType(String type) {
    sortType = type;
    update();
  }

  // 确认筛选
  Future<void> confirmFilter() async {
    Get.back(); // 关闭弹窗

    // 重新加载商品数据，应用新的排序
    if (currentClassId != null) {
      await _filterProductsByCategory(currentClassId!);
    }
  }

  // 构建筛选弹窗UI
  Widget _buildFilterBottomSheet() {
    return GetBuilder<ShopController>(
      builder: (controller) {
        return Container(
          decoration: const BoxDecoration(
            image: DecorationImage(
              fit: BoxFit.fitWidth,
              image: CachedNetworkImageProvider(
                'https://gluz-oss.oss-cn-beijing.aliyuncs.com/shopstatic/filter_bg.png',
              ),
            ),
            borderRadius: BorderRadius.only(
              topLeft: Radius.circular(20),
              topRight: Radius.circular(20),
            ),
          ),
          child: SafeArea(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                // 标题栏
                Container(
                  padding: const EdgeInsets.symmetric(
                    horizontal: 20,
                    vertical: 16,
                  ),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(
                        '排序'.tr,
                        style: const TextStyle(
                          fontSize: 18,
                          fontWeight: FontWeight.bold,
                          color: Colors.black,
                        ),
                      ),
                      InkWell(
                        onTap: closeFilter,
                        child: const Icon(
                          Icons.highlight_remove,
                          size: 22,
                          color: Colors.black,
                        ),
                      ),
                    ],
                  ),
                ),
                // 排序选项
                Container(
                  padding: const EdgeInsets.symmetric(horizontal: 16),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceAround,
                    children: sortOptions.entries.map((entry) {
                      final isSelected = sortType == entry.key;
                      return InkWell(
                        onTap: () => selectSortType(entry.key),
                        child: Container(
                          padding: const EdgeInsets.symmetric(
                            horizontal: 10,
                            vertical: 5,
                          ),
                          decoration: BoxDecoration(
                            color: Colors.white,
                            borderRadius: BorderRadius.circular(12),
                            border: Border.all(
                              color: isSelected
                                  ? AppColors.color_278AFF
                                  : Colors.transparent,
                              width: 1,
                            ),
                          ),
                          child: Text(
                            entry.value.tr,
                            style: TextStyle(
                              fontSize: 11,
                              color: isSelected
                                  ? AppColors.color_278AFF
                                  : Colors.black,
                              fontWeight: isSelected
                                  ? FontWeight.bold
                                  : FontWeight.normal,
                            ),
                          ),
                        ),
                      );
                    }).toList(),
                  ),
                ),
                // 确定按钮
                Container(
                  width: double.infinity,
                  padding: const EdgeInsets.all(20),
                  child: ElevatedButton(
                    onPressed: confirmFilter,
                    style: ElevatedButton.styleFrom(
                      backgroundColor: AppColors.color_278AFF,
                      foregroundColor: Colors.white,
                      padding: const EdgeInsets.symmetric(vertical: 12),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(8),
                      ),
                    ),
                    child: Text(
                      '确定'.tr,
                      style: const TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  // 商品点击
  void onProductTap(ShopListEntity product) {
    // Get.toNamed(Routes.PRODUCT_DETAIL, arguments: product.id);
    Get.toNamed(Routes.PRODUCT_DETAIL, arguments: '1947091651451453442');
  }

  // 下拉刷新
  Future<void> onRefresh() async {
    // 模拟网络请求延迟
    await Future.delayed(const Duration(seconds: 1));

    // 重新加载数据
    _loadPrimaryCategoriesData();
  }
}
